var initMapResult = [];
function initMap(map_name,start_poi,end_poi,ways_poi,mapType='poi') {
    $("#"+map_name).hide();
    //格式化
    start_poi = transStringToFloat(start_poi);
    end_poi = transStringToFloat(end_poi);
    var w_poi = [];
    var flightPlanCoordinates = [];
    flightPlanCoordinates.push(start_poi);
    if(ways_poi.length>0){
        $.each(ways_poi,function(i,v){
            if(v.lat!='' && v.lat!=null && v.lat!='0' && v.lng!='' && v.lng!=null && v.lng!='0' ){
                w_poi.push({location:{'lat':parseFloat(v.lat),"lng":parseFloat(v.lng)}});
                var w_point = transStringToFloat(v);
                flightPlanCoordinates.push(w_point);
            }
        })
    }
    flightPlanCoordinates.push(end_poi);

    var map = new google.maps.Map(document.getElementById(map_name), {
        zoom: 12,
        center: {lat: 39.316568, lng: -101.503765}  // 美国
    });

    var directionsService = new google.maps.DirectionsService;
    var directionsDisplay = new google.maps.DirectionsRenderer({
        draggable: false,
        map: map,
        suppressMarkers: true,//是否取消标点
        //suppressPolylines: true,//是否取消路线
        //panel: document.getElementById('right-panel')
    });
    //清空页面存在全程预计时长的节点
    if($("#totle_duration").length>0){
        document.getElementById('totle_duration').innerHTML = "全程预计时长：0 h";
    }
    //清空页面存在全程预计车程的节点
    if($("#totle_total").length>0){
        document.getElementById('totle_total').innerHTML = "全程预计车程：0 km";
    }
    directionsDisplay.addListener('directions_changed', function() {
        computeTotalDistance(directionsDisplay.getDirections());
    });

    displayRoute(start_poi, end_poi, w_poi,directionsService,directionsDisplay,map_name);

    var features = [];
    //点击显示悬浮框
    function clickMarker(infoWindow,marker,content)
    {
        google.maps.event.addListener(marker,'click',function(){
            infoWindow.setContent(content);
            infoWindow.open(map,marker);
        })
    }

    $.each(flightPlanCoordinates,function(i,v){
        var name = v.name;
        if(mapType!='poi'){
            name = v.name+"("+v.eng_name+")";
        }
        features.push({
            position:new google.maps.LatLng(parseFloat(v.lat), parseFloat(v.lng)),
            type: 'info',
            content:"<p data-type='"+v.type+"' data-id='"+v.id+"'>"+name+"<p>"
        })
    });
    var markers = [];
    for (var i = 0; i < features.length; i++) {
        var marker = new google.maps.Marker({
            position: features[i].position,
            icon: {
                url : '/icon/googlemap/marker'+(i+1)+'.png',
                scaledSize: new google.maps.Size(27, 43), // scaled size
            },
            map: map
        });
        var content = features[i].content;
        markers.push(marker);
        //展示悬浮框
        var infowindow = new google.maps.InfoWindow;
        //绑定点击时间方法
        clickMarker(infowindow,marker,content);
        infowindow.setContent(content);
        infowindow.open(map,marker);
    }
    //显示折线方案
    // var flightPath = new google.maps.Polyline({
    //     path: flightPlanCoordinates,
    //     geodesic: true,
    //     strokeColor: '#FF0000',
    //     strokeOpacity: 1.0,
    //     strokeWeight: 2
    // });
    // flightPath.setMap(map);

    //展示最佳视野的函数
    function setVeiwPort(markers) {
        var bounds = new google.maps.LatLngBounds();
        //读取标注点的位置坐标，加入LatLngBounds
        for(var i = 0;i < markers.length;i++){
            bounds.extend(markers[i].getPosition());
        }
        //调整map，使其适应LatLngBounds,实现展示最佳视野的功能
        setTimeout(function(){
            map.fitBounds(bounds);
        },1000)
    }
    setVeiwPort(markers);
}

function displayRoute(origin, destination, ways_poi,service, display,map_name) {
    service.route({
        origin: origin,
        destination: destination,
        waypoints: ways_poi,
        travelMode: 'DRIVING',
        provideRouteAlternatives:true,
        avoidTolls: false
    }, function(response, status) {
        if (status === 'OK') {
            display.setDirections(response);
            $("#"+map_name).show()
            checkExistMapName(map_name,'true')
        } else {
            $("#"+map_name).show();
            checkExistMapName(map_name,'false')
        }

    });
}

function computeTotalDistance(result) {
    var total = 0;
    var duration = 0;
    var myroute = result.routes[0];
    for (var i = 0; i < myroute.legs.length; i++) {
        total += myroute.legs[i].distance.value;
        duration += myroute.legs[i].duration.value;
    }
    total = total / 1000;
    duration = duration / ( 60 * 60 );
    duration = duration.toFixed(2);
    total = total.toFixed(2);
    //页面存在全程预计时长的节点
    if($("#totle_duration").length>0){
        document.getElementById('totle_duration').innerHTML = "全程预计时长：" + duration + ' h';
    }
    //页面存在全程预计车程的节点
    if($("#totle_total").length>0){
        document.getElementById('totle_total').innerHTML = "全程预计车程：" + total + ' km';
    }
    //document.getElementById('totle_duration').innerHTML = "全程预计时长：" + duration + ' h';
    //document.getElementById('totle_total').innerHTML = "全程预计车程：" + total + ' km';

    //document.getElementById('total').innerHTML = total + ' km';
}

function checkExistMapName(map_name,res)
{
    var exist_index = -1;
    $.each(initMapResult,function(i,v){
        if(v.name==map_name){
            exist_index = i;
            console.log(v.name,map_name,exist_index);
            return false;
        }
    })

    if(exist_index != -1){
        initMapResult[exist_index] = {'name':map_name,'res':res};
    }else{
        initMapResult.push({'name':map_name,'res':res})
    }
}

function checkMapResult(map_name){
    var result = true;
    $.each(initMapResult,function(i,v){
        if(v.name==map_name && v.res=='false'){
            result = false;
            return false;
        }
    })
    return result;
}

//将字符串的经纬度转换成float
function transStringToFloat(point)
{
    point.lat = parseFloat(point.lat);
    point.lng = parseFloat(point.lng);

    return point;
}
